package net.wicp.tams.plugin.constant;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.FileUtils;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.IOUtil;

public enum Env {
	dev(),

	test(),

	pre(),

	prd();

	private final String repository;
	private final String branch;
	private final String user;
	private final String pwd;

	// 不能用static,否则会迟于构造函数执行
	{
		String workDirPath = System.getProperty("user.home");
		File globleDir = new File(String.format("%s/%s", workDirPath, ".tams"));
		if (!globleDir.exists()) {
			try {
				FileUtils.forceMkdir(globleDir);
			} catch (IOException e) {
				throw new RuntimeException("创建home目录" + globleDir.getPath() + "失败");
			}
		}
		File confFile = new File(globleDir, "env.properties");
		if (!confFile.exists()) {
			StringBuffer buf = new StringBuffer("\n 需要文件 " + confFile.getPath() + ",文件中包括下列属性:\n");
			buf.append(
					"库地址(http)---------------------------分支(配置文件所在)------------------用户名---------------------------密码-------------------------\n");
			buf.append(
					"示例:http://10.1.114.52/tpyb/tpyb-profile-sit.git------develop------------tpybops--------------------------tpybops123---------------------\n");
			buf.append(
					"configserver.dev.repository------------configserver.dev.branch------------configserver.dev.user------------configserver.dev.pwd------------\n");
			buf.append(
					"configserver.test.repository-----------configserver.test.branch-----------configserver.test.user-----------configserver.test.pwd------------\n");
			buf.append(
					"configserver.pre.repository------------configserver.pre.branch------------configserver.pre.user------------configserver.pre.pwd------------\n");
			buf.append(
					"configserver.pro.repository------------configserver.pro.branch------------configserver.pro.user------------configserver.pro.pwd------------\n");
			throw new RuntimeException(buf.toString());
		}
		Properties properties = IOUtil.fileToProperties(confFile);
		Conf.overProp(properties);
	}

	private Env() {
		Map<String, String> proptemp = Conf.getPre("configserver." + this.name(), true);
		if (!proptemp.containsKey("repository") || !proptemp.containsKey("branch") || !proptemp.containsKey("user")
				|| !proptemp.containsKey("pwd")) {
			System.out.println(this.name() + "缺少配置");
		}
		this.repository = proptemp.get("repository");
		this.branch = proptemp.get("branch");
		this.user = proptemp.get("user");
		this.pwd = proptemp.get("pwd");
	}

	public String getUser() {
		return user;
	}

	public String getPwd() {
		return pwd;
	}

	public String getRepository() {
		return repository;
	}

	public String getBranch() {
		return branch;
	}
}
